import { useEffect } from 'react';
import echarts from 'echarts';
import 'echarts-gl';
import 'echarts/lib/chart/pie';
import 'echarts/lib/component/title';

function useECharts(chartRef, config) {
  let chartInstance = null;
  function renderChart() {
    const renderedInstance = echarts.getInstanceByDom(chartRef.current);
    if (renderedInstance) {
      chartInstance = renderedInstance;
    } else {
      chartInstance = echarts.init(chartRef.current);
    }

    chartInstance.setOption(config);
  }

  // 更新组件
  useEffect(() => {
    renderChart();
  }, [config]);

  // 组件卸载后释放内存
  useEffect(() => {
    return () => {
      // eslint-disable-next-line no-unused-expressions
      chartInstance && chartInstance.dispose();
    };
  }, []);
}

export default useECharts;
